package org.client.iot.util;



import static org.client.iot.constant.GlobeConstant.SystemConfig.MMKV_FILE_NAME;

import com.tencent.mmkv.MMKV;

import java.util.Map;

/**
 * 所属包：org.teapot.ecg_health.utils
 * 作者：Administrator on 2020/8/18 13:22
 */
public class MMKVUtils {
    private static final String TAG = "MMKVUtils:";

    private static MMKVUtils mmkvUtils;


    private static MMKV mMkv = null;

    private MMKVUtils() {
        mMkv = MMKV.mmkvWithID(MMKV_FILE_NAME, MMKV.SINGLE_PROCESS_MODE);
    }

    public static MMKVUtils getInstance(){
        if(mmkvUtils==null){
            synchronized (MMKVUtils.class){
                if(mmkvUtils==null){
                    mmkvUtils = new MMKVUtils();
                }
            }
        }
        return mmkvUtils;
    }
    /**
     * 保存数据的方法，我们需要拿到保存数据的具体类型，然后根据类型调用不同的保存方法
     *
     * @param key
     * @param object
     */
    public void put(String key, Object object) {
        if (object instanceof String) {
            mMkv.encode(key, (String) object);
        } else if (object instanceof Integer) {
            mMkv.encode(key, (Integer) object);
        } else if (object instanceof Boolean) {
            mMkv.encode(key, (Boolean) object);
        } else if (object instanceof Float) {
            mMkv.encode(key, (Float) object);
        } else if (object instanceof Long) {
            mMkv.encode(key, (Long) object);
        } else {
            mMkv.encode(key, object.toString());
        }
    }

    public Object get( String key, Object defaultObject) {

        if (defaultObject instanceof String) {
            return mMkv.decodeString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return mMkv.decodeInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return mMkv.decodeBool(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return mMkv.decodeFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return mMkv.decodeLong(key, (Long) defaultObject);
        }else{
            return mMkv.decodeString(key, (String) defaultObject);
        }

    }

    /**
     * 清除所有数据
     */
    public void clear() {
        mMkv.clear().commit();
    }

    /**
     * 返回所有的键值对
     * @return
     */
    public  Map<String, ?> getAll() {
        return mMkv.getAll();
    }

    /**
     * 移除某个key值已经对应的值
     *
     * @param key
     */
    public  void remove(String key) {
       mMkv.remove(key);
    }

    /**
     * 查询某个key是否已经存在
     * @param key
     * @return
     */
    public  boolean contains(String key) {
        return mMkv.contains(key);
    }

}
